package com.wfm.atomic;

import java.util.concurrent.atomic.AtomicStampedReference;

public class AtomicStampedReferenceDemo {
    public static void main(String[] args) {
        // 初始值为 10，初始版本号为 0
        AtomicStampedReference<Integer> value = new AtomicStampedReference<>(10, 0);

        // 获取初始值和版本号
        int[] stampHolder = new int[1];
        int oldValue = value.get(stampHolder);
        int oldStamp = stampHolder[0];
        System.out.println("Thread A: Read value = " + oldValue + ", stamp = " + oldStamp);

        // 线程 B 修改值
        value.compareAndSet(10, 20, oldStamp, oldStamp + 1); // A -> B，版本号 +1
        value.compareAndSet(20, 10, oldStamp + 1, oldStamp + 2); // B -> A，版本号 +1

        // 线程 A 执行 CAS 操作
        boolean success = value.compareAndSet(10, 30, oldStamp, oldStamp + 1);
        System.out.println("Thread A: CAS success = " + success); // 输出 false
    }
}